package com.zlx.sharelive.activity;

import android.app.Dialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.zlx.module_base.base_ac.BaseAc;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.CommentBean;
import com.zlx.module_base.base_api.res_data.DeleteFocusedBean;
import com.zlx.module_base.base_api.res_data.ShortVideoBean;
import com.zlx.module_base.base_api.res_data.ShortVideoBody;
import com.zlx.module_base.base_api.res_data.ShortVideoCommentListBean;
import com.zlx.module_base.base_api.res_data.UpdateUserBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.StringUt;
import com.zlx.module_base.base_util.TimeUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.view.CustomVideoView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;

/**
 * 短视频详情
 */
public class ShortVideoDetailsAc extends BaseAc {


    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tv_link)
    TextView tv_link;
    @BindView(R.id.tv_text)
    TextView tv_text;
    @BindView(R.id.videoView)
    CustomVideoView videoView;
    @BindView(R.id.iv_attention)
    ImageView iv_attention;
    @BindView(R.id.tv_comment)
    TextView tv_comment;
    @BindView(R.id.tv_fabulous)
    TextView tv_fabulous;
    @BindView(R.id.iv_fabulous)
    ImageView iv_fabulous;

    private String pid = "-1";
    private String uid;
    private String id;
    private String video;

    private List<ShortVideoCommentListBean.InfoDTO> mList = new ArrayList<>();
    private List<ShortVideoCommentListBean.InfoDTO> mList2 = new ArrayList<>();
    private CommonRecyclerViewAdapter<ShortVideoCommentListBean.InfoDTO> mAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.ac_short_video_details;
    }

    @Override
    public void initViews() {
        super.initViews();

        id = getIntent().getStringExtra("id");
        video = getIntent().getStringExtra("video");
        getShortVideo(id);

        Uri uri = Uri.parse(video);
        videoView.setVideoURI(uri);
        //创建MediaController对象
        MediaController mediaController = new MediaController(this);
        mediaController.setVisibility(View.GONE);
        //VideoView与MediaController建立关联
        videoView.setMediaController(mediaController);
        //让VideoView获取焦点
        videoView.requestFocus();
        videoView.start();

        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.setLooping(true);
            }
        });
    }

    private void getShortVideo(String id) {
        ShortVideoBody shortVideoBody = new ShortVideoBody();
        shortVideoBody.setId(Integer.valueOf(id));
        ApiUtil.getVideoApi().getShortVideo(SPUtil.getToken(this), shortVideoBody).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<ShortVideoBean>>() {
            @Override
            public void onSuccess(ApiResponse<ShortVideoBean> data) {
                if (null != data.getData()) {
                    if (null != data.getData().getInfo()) {
                        if (data.getData().getInfo().size() > 0) {
                            setShortVideo(data.getData().getInfo().get(0));
                        }
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    private void setShortVideo(ShortVideoBean.InfoDTO data) {
        uid = data.getUid();
        tv_nickname.setText("@" + data.getNickName());
        tv_link.setText(data.getLikes());
        tv_text.setText(data.getTitle());
        if (data.getIfFollow().equals("2")) {
            iv_attention.setVisibility(View.VISIBLE);
        } else {
            iv_attention.setVisibility(View.GONE);
        }
        tv_comment.setText(data.getComments());
        if (data.getIfLike().equals("1")) {
            //点赞
            iv_fabulous.setImageResource(R.mipmap.fabulous_img_true);
        } else {
            iv_fabulous.setImageResource(R.mipmap.fabulous_false_1);
        }
        tv_fabulous.setText(data.getLikes());
    }

    @OnClick({R.id.ll_comment, R.id.iv_attention, R.id.fl_head, R.id.ll_fabulous,
            R.id.iv_private_letter})
    public void setOnClick(View view) {
        switch (view.getId()) {
            case R.id.ll_comment:
                getShortVideoCommentList();
                break;
            case R.id.iv_attention:
                //关注
                addorDeleteFocused();
                break;
            case R.id.fl_head:
                String id = (String) SPUtil.get(this, Constants.SP_ID, "");
                if (id.equals(uid)) {
                    //如果是自己
                    startActivity(new Intent(this, HomepageAc.class));
                } else {
                    startActivity(new Intent(this, OthersHomepageAc.class)
                            .putExtra("uid", uid));
                }
                break;
            case R.id.ll_fabulous:
                //点赞
                addLike();
                break;
            case R.id.iv_private_letter:
                //私聊天
                Conversation.ConversationType conversationType = Conversation.ConversationType.PRIVATE;
                String targetId = uid;
                String title = "标题";
                Long fixedMsgSentTime = System.currentTimeMillis();
                RongIM.getInstance().startConversation(ShortVideoDetailsAc.this, conversationType, targetId, title, fixedMsgSentTime);
                break;

        }
    }

    /**
     * 点赞视频
     */
    private void addLike() {
        ApiUtil.getServiceApi().addLike(SPUtil.getToken(this),
                id,
                "1"
        ).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<UpdateUserBean>>() {
            @Override
            public void onSuccess(ApiResponse<UpdateUserBean> data) {
                if (null != data) {
                    if (null != data.getData()) {
                        if (data.getData().getCode() == 0) {
                            if (null != data.getData().getInfo()) {
                                if (data.getData().getInfo().size() > 0) {
                                    if (data.getData().getInfo().get(0).getIsLike().equals("1")) {
                                        //点赞
                                        iv_fabulous.setImageResource(R.mipmap.fabulous_img_true);
                                    } else {
                                        iv_fabulous.setImageResource(R.mipmap.fabulous_false_1);
                                    }
                                    tv_fabulous.setText(data.getData().getInfo().get(0).getNums());
                                }
                            }
                        }
                    }
                }
            }
        }));
    }

    private void addorDeleteFocused() {
        DeleteFocusedBean deleteFocusedBean = new DeleteFocusedBean();
        deleteFocusedBean.setUid(uid);
        ApiUtil.getUserApi().addorDeleteFocused(SPUtil.getToken(this),
                deleteFocusedBean).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                getShortVideo(id);
            }
        }));
    }

    /**
     * 短视频评论
     */
    private void getShortVideoCommentList() {
        ApiUtil.getVideoApi().getShortVideoCommentList(SPUtil.getToken(this),
                id).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<ShortVideoCommentListBean>>() {
            @Override
            public void onSuccess(ApiResponse<ShortVideoCommentListBean> data) {
                mList.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            mList.addAll(data.getData().getInfo());
                        }
                    }
                }
                mList2.clear();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getPid().equals("-1")) {
                        mList2.add(mList.get(i));
                    }
                }
                dialogMessage();
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 短视频评论
     */
    private void getShortVideoCommentList2() {
        ApiUtil.getVideoApi().getShortVideoCommentList(SPUtil.getToken(this),
                id).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<ShortVideoCommentListBean>>() {
            @Override
            public void onSuccess(ApiResponse<ShortVideoCommentListBean> data) {
                mList.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        if (null != data.getData().getInfo()) {
                            mList.addAll(data.getData().getInfo());
                        }
                    }
                }
                mList2.clear();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getPid().equals("-1")) {
                        mList2.add(mList.get(i));
                    }
                }
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }));
    }

    /**
     * 弹出评论
     */
    private void dialogMessage() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(this, R.layout.dialog_message, null);
        dialog.setContentView(view);

        EditText et_text = view.findViewById(R.id.et_text);

        TextView tv_message_number = view.findViewById(R.id.tv_message_number);

        tv_message_number.setText(mList.size() + "条评论");

        TextView tv_comm = view.findViewById(R.id.tv_comm);

        tv_comm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (StringUt.isEmpty(et_text.getText().toString().trim())) {
                    Toast.makeText(ShortVideoDetailsAc.this, "内容不可为空", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    setComment(et_text.getText().toString().trim(), et_text, pid);
                }
            }
        });

        RecyclerView dialog_recycler = view.findViewById(R.id.dialog_recycler);

        dialog_recycler.setLayoutManager(new LinearLayoutManager(this));

        mAdapter = new CommonRecyclerViewAdapter<ShortVideoCommentListBean.InfoDTO>(this, mList2) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, ShortVideoCommentListBean.InfoDTO entity, int position) {
                GlideImgManager.glideLoader(ShortVideoDetailsAc.this, entity.getAvatar(), holder.getView(R.id.iv_review_head), 0);
                holder.setText(R.id.tv_review_nickname, entity.getNickname());
                holder.setText(R.id.tv_review_text, entity.getComment());
                ImageView iv_vip = holder.getView(R.id.iv_vip);
                ImageView iv_goddess = holder.getView(R.id.iv_goddess);
                if (entity.getIsvip().equals("2")) {
                    iv_vip.setVisibility(View.VISIBLE);
                } else {
                    iv_vip.setVisibility(View.GONE);
                }
                if (entity.getAuthentication().equals("1")) {
                    iv_goddess.setVisibility(View.VISIBLE);
                } else {
                    iv_goddess.setVisibility(View.GONE);
                }
                try {
                    holder.setText(R.id.tv_time, TimeUtil.getTimeStringAutoShort2(TimeUtil.ConverToDate(entity.getCreateTime()), true));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                RecyclerView rv_review = holder.getView(R.id.rv_review);
                rv_review.setLayoutManager(new LinearLayoutManager(ShortVideoDetailsAc.this));

                List<ShortVideoCommentListBean.InfoDTO> newList = new ArrayList<>();
                newList.clear();
                //1级评论数据
                for (int i = 0; i < mList.size(); i++) {
                    if (!com.zlx.sharelive.utils.StringUt.isEmpty(mList.get(i).getPid())) {
                        if (!mList.get(i).getPid().equals("-1")) {
                            if (mList.get(i).getPid().equals(entity.getId())) {
                                newList.add(mList.get(i));
                            }
                        }
                    }
                }
                //2级评论数据
                for (int i = 0; i < mList.size(); i++) {
                    if (!com.zlx.sharelive.utils.StringUt.isEmpty(mList.get(i).getPid())) {
                        for (int j = 0; j < newList.size(); j++) {
                            if (!com.zlx.sharelive.utils.StringUt.isEmpty(newList.get(j).getPid())) {
                                if (mList.get(i).getPid().equals(newList.get(j).getId())) {
                                    newList.add(mList.get(i));
                                }
                            }
                        }
                    }
                }
                //2级评论的回复
                for (int i = 0; i < newList.size(); i++) {
                    for (int j = 0; j < newList.size(); j++) {
                        if (newList.get(i).getPid().equals(newList.get(j).getId())) {
                            newList.get(i).setFlag(true);
                            newList.get(i).setName(newList.get(j).getNickname());
                        }
                    }
                }

                CommonRecyclerViewAdapter<ShortVideoCommentListBean.InfoDTO> adapter = new CommonRecyclerViewAdapter<ShortVideoCommentListBean.InfoDTO>(ShortVideoDetailsAc.this, newList) {
                    @Override
                    public void convert(CommonRecyclerViewHolder holder, ShortVideoCommentListBean.InfoDTO entity, int position) {
                        ImageView iv_review_head = holder.getView(R.id.iv_review_head);
                        GlideImgManager.glideLoader(ShortVideoDetailsAc.this, entity.getAvatar(), iv_review_head, 0);
                        holder.setText(R.id.tv_review_nickname, entity.getNickname());
                        holder.setText(R.id.tv_review_text, entity.getComment());
                        if (entity.isFlag() == true) {
                            ((LinearLayout) holder.getView(R.id.ll_reply)).setVisibility(View.VISIBLE);
                            holder.setText(R.id.tv_nickname2, entity.getName());
                        } else {
                            ((LinearLayout) holder.getView(R.id.ll_reply)).setVisibility(View.GONE);
                        }

                        try {
                            holder.setText(R.id.tv_time, TimeUtil.getTimeStringAutoShort2(TimeUtil.ConverToDate(entity.getCreateTime()), true));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public int getLayoutViewId(int viewType) {
                        return R.layout.item_review2;
                    }
                };

                rv_review.setAdapter(adapter);

                adapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View v, int position) {
                        et_text.setHint("@" + newList.get(position).getNickname());
                        pid = newList.get(position).getId();
                    }
                });
            }

            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_review;
            }
        };

        dialog_recycler.setAdapter(mAdapter);

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                et_text.setHint("@" + mList2.get(position).getNickname());
                pid = mList2.get(position).getId();
            }
        });

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    private void setComment(String text, EditText et_text, String pid) {
        showLoading();
        CommentBean comment = new CommentBean();
        comment.setPid(pid);
        comment.setUid((String) SPUtil.get(this, Constants.SP_ID, ""));
        comment.setVid(id);
        comment.setComment(text);
        ApiUtil.getVideoApi().addComment(SPUtil.getToken(ShortVideoDetailsAc.this),
                comment
        ).observe(this, new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
            @Override
            public void onSuccess(ApiResponse<BaseBean> data) {
                showSuccess();
                if (data.getData().getCode() == 0) {
                    Toast.makeText(ShortVideoDetailsAc.this, "评论成功", Toast.LENGTH_SHORT).show();
                    et_text.setText("");
                    et_text.setHint("发表评论，分享自己的看法");
                    getShortVideoCommentList2();
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                showSuccess();
            }
        }));
    }


}
